//
//  CMNavBarAppDelegate.m
//  CMNavBar
//
//  Created by Chaiyasit Tayabovorn on 2/23/11.
//  Copyright 2011 CodeMobiles Co.,Ltd. All rights reserved.
//


#import "foodBViewController.h"
#import "CMNavBarAppDelegate.h"
#import "RootViewController.h"
#import "profileViewController.h"
#import "InfoViewController.h"
#import "foodAViewController.h"


@implementation CMNavBarAppDelegate

@synthesize window;
@synthesize navigationController;
@synthesize cars;
@synthesize isDBReady;

#define kFilename    @"data.sqlite"


+ (NSString *)dataFilePath {
    
    /* loaded from bundled file */
    //return [[NSBundle mainBundle] pathForResource:kFilename ofType:nil];
    
    /* loaded or created from Document folder runtime */ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);//ดีง path ทั้งหมด
    NSString *documentsDirectory = [paths objectAtIndex:0];
    return [documentsDirectory stringByAppendingPathComponent:kFilename];
}
#pragma mark -
#pragma mark Application lifecycle

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {    
    
    // Override point for customization after application launch.
    RootViewController *rootView = [[RootViewController alloc]initWithNibName:@"RootViewController" bundle:nil];
    self.navigationController = [[UINavigationController alloc] initWithRootViewController:rootView];
    // Add the navigation controller's view to the window and display.
    self.window.rootViewController = self.navigationController;
    [self.window addSubview:navigationController.view];
    [self.window makeKeyAndVisible];
    
    self.isDBReady = NO;
    
    
    NSString *dbPath = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"sqlite"];
    NSLog(@"dbPath : %@", dbPath);
    
    
    db = [[FMDatabase databaseWithPath:dbPath] retain];
    if (![db open]) {
        NSLog(@"Could not open DB");
    }else{
        self.isDBReady = YES;
        
    }
   
    return YES;


 
}


- (void)applicationWillResignActive:(UIApplication *)application {
    /*
     Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
     Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
     */
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    /*
     Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. 
     If your application supports background execution, called instead of applicationWillTerminate: when the user quits.
     */
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    /*
     Called as part of  transition from the background to the inactive state: here you can undo many of the changes made on entering the background.
     */
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    /*
     Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
     */
}


- (void)applicationWillTerminate:(UIApplication *)application {
    /*
     Called when the application is about to terminate.
     See also applicationDidEnterBackground:.
     */
}


#pragma mark -
#pragma mark Memory management

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
    /*
     Free up as much memory as possible by purging cached data objects that can be recreated (or reloaded from disk) later.
     */
}


- (void)dealloc {
	[navigationController release];
	[window release];
    [cars release];
	[super dealloc];
}

-(NSMutableArray *)getProjects{
    
    NSMutableArray *projects = [[NSMutableArray alloc] init];
    
    
    FMResultSet *rsProject = [db executeQuery:@"select * from food where bloodF = 'A' "];
    while ([rsProject next]) {
        
        food *foods = [[food alloc] init];
        
        foods._id = [rsProject intForColumn:@"idF"];
        foods.name = [rsProject stringForColumn:@"nameF"];
        foods.calorie = [rsProject stringForColumn:@"calorieF"]; 
        foods.typeF = [rsProject stringForColumn:@"typeF"];
        //foods.amountf = [rsProject stringForColumn:@"amountf"];
        foods.bloodf = [rsProject stringForColumn:@"bloodF"];
        [projects addObject:foods];
        
//        NSLog(@"Name Project : %@", food.name);
//        NSLog(@"Detail : %@", ckProject.detail);
//        NSLog(@"Fund : %d", ckProject.fund);
//        NSLog(@"Start Date : %@", ckProject.startDate);
        
    }
    
    [rsProject close];
    
    NSLog(@"found %d", projects.count);
    
    return projects;
    
}   


-(BOOL)deleteA:(NSInteger)idDelete{
    
   // NSMutableArray *deleteA = [[NSMutableArray alloc] init];
    BOOL isSuccess = YES;
    NSLog(@"%d",idDelete);
   NSString *pst = [NSString stringWithFormat:@"delete from food where idF = %d ",idDelete ];
   // NSString *pst = @"insert into food (nameF,calorieF,typeF,bloodF) VALUES ('test1','test1','test1','test1')";
    NSLog(@"pst : %@",pst);
   
    [db executeUpdate:pst];
    if (!db) {
        NSLog(@"Delete Failed");
        isSuccess = NO;
    }
    NSLog(@"Error %d: %@", [db lastErrorCode], [db lastErrorMessage]);
    NSLog(@"%@",pst);    
    
    return isSuccess;
    
}


-(NSMutableArray *)getProjectsB{
    
    NSMutableArray *projects = [[NSMutableArray alloc] init];
    
    
    FMResultSet *rsProject = [db executeQuery:@"select * from food where bloodF = 'B'"];
    while ([rsProject next]) {
        
        food *foods = [[food alloc] init];
        
        foods._id = [rsProject intForColumn:@"idF"];
        foods.name = [rsProject stringForColumn:@"nameF"];
        foods.calorie = [rsProject stringForColumn:@"calorieF"]; 
        foods.typeF = [rsProject stringForColumn:@"typeF"];
        //foods.amountf = [rsProject stringForColumn:@"amountf"];
        foods.bloodf = [rsProject stringForColumn:@"bloodF"];
        
        [projects addObject:foods];
        
        //        NSLog(@"Name Project : %@", food.name);
        //        NSLog(@"Detail : %@", ckProject.detail);
        //        NSLog(@"Fund : %d", ckProject.fund);
        //        NSLog(@"Start Date : %@", ckProject.startDate);
        
    }
    
    [rsProject close];
    
    NSLog(@"found %d", projects.count);
    
    return projects;
    
}
-(NSMutableArray *)getProjectsO{
    
    NSMutableArray *projects = [[NSMutableArray alloc] init];
    
    
    FMResultSet *rsProject = [db executeQuery:@"select * from food where bloodF = 'O'"];
    while ([rsProject next]) {
        
        food *foods = [[food alloc] init];
        
        foods._id = [rsProject intForColumn:@"idF"];
        foods.name = [rsProject stringForColumn:@"nameF"];
        foods.calorie = [rsProject stringForColumn:@"calorieF"]; 
        foods.typeF = [rsProject stringForColumn:@"typeF"];
        //foods.amountf = [rsProject stringForColumn:@"amountf"];
        foods.bloodf = [rsProject stringForColumn:@"bloodF"];
        
        [projects addObject:foods];
        
        //        NSLog(@"Name Project : %@", food.name);
        //        NSLog(@"Detail : %@", ckProject.detail);
        //        NSLog(@"Fund : %d", ckProject.fund);
        //        NSLog(@"Start Date : %@", ckProject.startDate);
        
    }
    
    [rsProject close];
    
    NSLog(@"found %d", projects.count);
    
    return projects;
    
}
-(NSMutableArray *)getProjectsAB{
    
    NSMutableArray *projects = [[NSMutableArray alloc] init];
    
    
    FMResultSet *rsProject = [db executeQuery:@"select * from food where bloodF = 'AB'"];
    while ([rsProject next]) {
        
        food *foods = [[food alloc] init];
        
        foods._id = [rsProject intForColumn:@"idF"];
        foods.name = [rsProject stringForColumn:@"nameF"];
        foods.calorie = [rsProject stringForColumn:@"calorieF"]; 
        foods.typeF = [rsProject stringForColumn:@"typeF"];
        //foods.amountf = [rsProject stringForColumn:@"amountf"];
        foods.bloodf = [rsProject stringForColumn:@"bloodF"];
        
        [projects addObject:foods];
        
        //        NSLog(@"Name Project : %@", food.name);
        //        NSLog(@"Detail : %@", ckProject.detail);
        //        NSLog(@"Fund : %d", ckProject.fund);
        //        NSLog(@"Start Date : %@", ckProject.startDate);
        
    }
    
    [rsProject close];
    
    NSLog(@"found %d", projects.count);
    
    return projects;
    
}


-(NSMutableArray *)getProjectsEA{
    
    NSMutableArray *projects = [[NSMutableArray alloc] init];
    
    
    FMResultSet *rsProject = [db executeQuery:@"select * from exercise where bloodE = 'A'"];
    while ([rsProject next]) {
        
        exercise *exercises = [[exercise alloc] init];
        
        exercises._idE = [rsProject intForColumn:@"idE"];
        exercises.nameE = [rsProject stringForColumn:@"nameE"];
        exercises.calorieE = [rsProject stringForColumn:@"calorieE"]; 
        exercises.bloodE = [rsProject stringForColumn:@"bloodE"];
        
        [projects addObject:exercises];
        
        //        NSLog(@"Name Project : %@", food.name);
        //        NSLog(@"Detail : %@", ckProject.detail);
        //        NSLog(@"Fund : %d", ckProject.fund);
        //        NSLog(@"Start Date : %@", ckProject.startDate);
        
    }
    
    [rsProject close];
    
    NSLog(@"found %d", projects.count);
    
    return projects;
    
}

-(NSMutableArray *)getProjectsEB{
    
    NSMutableArray *projects = [[NSMutableArray alloc] init];
    
    
    FMResultSet *rsProject = [db executeQuery:@"select * from exercise where bloodE = 'B'"];
    while ([rsProject next]) {
        
        exercise *exercises = [[exercise alloc] init];
        
        exercises._idE = [rsProject intForColumn:@"idE"];
        exercises.nameE = [rsProject stringForColumn:@"nameE"];
        exercises.calorieE = [rsProject stringForColumn:@"calorieE"]; 
        exercises.bloodE = [rsProject stringForColumn:@"bloodE"];
        
        [projects addObject:exercises];
        
        //        NSLog(@"Name Project : %@", food.name);
        //        NSLog(@"Detail : %@", ckProject.detail);
        //        NSLog(@"Fund : %d", ckProject.fund);
        //        NSLog(@"Start Date : %@", ckProject.startDate);
        
    }
    
    [rsProject close];
    
    NSLog(@"found %d", projects.count);
    
    return projects;
    
}
-(NSMutableArray *)getProjectsEO{
    
    NSMutableArray *projects = [[NSMutableArray alloc] init];
    
    
    
    FMResultSet *rsProject = [db executeQuery:@"select * from exercise where bloodE = 'O'"];
    while ([rsProject next]) {
        
        exercise *exercises = [[exercise alloc] init];
        
        exercises._idE = [rsProject intForColumn:@"idE"];
        exercises.nameE = [rsProject stringForColumn:@"nameE"];
        exercises.calorieE = [rsProject stringForColumn:@"calorieE"]; 
        exercises.bloodE = [rsProject stringForColumn:@"bloodE"];
        
        [projects addObject:exercises];
        
    }
    
    [rsProject close];
    
    NSLog(@"found %d", projects.count);
    
    return projects;
    
}
-(NSMutableArray *)getProjectsEAB{
    
    NSMutableArray *projects = [[NSMutableArray alloc] init];
    
    
    FMResultSet *rsProject = [db executeQuery:@"select * from exercise where bloodE = 'AB'"];
    while ([rsProject next]) {
        
        exercise *exercises = [[exercise alloc] init];
        
        exercises._idE = [rsProject intForColumn:@"idE"];
        exercises.nameE = [rsProject stringForColumn:@"nameE"];
        exercises.calorieE = [rsProject stringForColumn:@"calorieE"]; 
        exercises.bloodE = [rsProject stringForColumn:@"bloodE"];
        
        [projects addObject:exercises];
        
    }
    
    [rsProject close];
    
    NSLog(@"found %d", projects.count);
    
    return projects;
    
}

-(BOOL)saveProjects:(food *)project{
    
    BOOL isSuccess = YES;
    
    
    //    [db executeUpdate:@"insert into projects (name, detail, start_date, end_date, fund, photo_path) values (?, ?, ?, ?, ?, ?)", project.name, project.detail, project.startDate, project.endDate, project.fund, project.photoPath];
    
    NSLog(@"++++++++++++++++++++++++++++++++");
    NSLog(@"Name %@", project.name);
    NSLog(@"Name %@", project.calorie);
    NSLog(@"++++++++++++++++++++++++++++++++");
    
    
  //[db executeUpdate:@"insert into projects (name, detail, fund, start_date, is_deleted) values (?, ?, ?, ?, 0)", project.name, project.detail, [NSNumber numberWithInt:project.fund], project.startDate];
    //[db executeUpdate:@"insert into projects (name) values (?)", project.name,[NSNumber numberWithInt:project.calorie]];

    
    if ([db hadError]) {
        NSLog(@"Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        isSuccess = NO;
    }
    
    
    return isSuccess;
    
}
#pragma mark - openProject:closedProject
-(BOOL)openProject:(food *)ckProject{
    
    BOOL isSuccess = YES;
    [db executeUpdate:@"update food set is_closed = 1 where id=?", [NSNumber numberWithInt:ckProject._id]];
    
    if ([db hadError]) {
        NSLog(@"Open Project Error %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        isSuccess = NO;
    }
    return isSuccess;
}
-(BOOL)closedProject:(food *)ckProject{
    
    BOOL isSuccess = YES;
    [db executeUpdate:@"update food set is_closed = 0 where id=?", [NSNumber numberWithInt:ckProject._id]];
    
    if ([db hadError]) {
        NSLog(@"Closed Project Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        isSuccess = NO;
    }
    return isSuccess;
    
    
}
#pragma mark - deleteProject


-(BOOL)deleteProject:(food *)ckProject {
    
    
    BOOL isSuccess = YES;
    
    [db executeUpdate:@"update projects set is_deleted = 1 where id=?", [NSNumber numberWithInt:ckProject._id]];
    
    if ([db hadError]) {
        NSLog(@"Delete Project Err %d: %@", [db lastErrorCode], [db lastErrorMessage]);
        isSuccess = NO;
    }
    return isSuccess;
    
}
+ (void)delete:(NSString *)which; {
    sqlite3 *database;
    if (sqlite3_open([[self dataFilePath] UTF8String], &database) != SQLITE_OK) {
        sqlite3_close(database);
        NSAssert(0, @"Failed to open database");
    }
    
    char *errorMsg;
    char *update = "DELETE FROM food WHERE name = (?);";
    sqlite3_stmt *stmt;
    if (sqlite3_prepare_v2(database, update, -1, &stmt, nil) == SQLITE_OK) {
        sqlite3_bind_text(stmt, 1, [which  UTF8String], -1, NULL);
        
        if (sqlite3_step(stmt) != SQLITE_DONE)
            NSAssert1(0, @"Error updating table: %s", errorMsg);
    }
    
    sqlite3_finalize(stmt);
    sqlite3_close(database);
}



@end

